package com.atguigu.flink.chapter07.state;

import com.atguigu.flink.bean.WaterSensor;
import com.atguigu.flink.util.AtguiguUtil;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.List;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/12/15 9:26
 */
public class Flink08_Keyed_State_Aggregate_1 {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        env
            .socketTextStream("hadoop162", 9999)
            .map(line -> {
                String[] data = line.split(",");
                return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
            })
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                
                private MapState<Integer, Object> vcState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    vcState = getRuntimeContext()
                        .getMapState(new MapStateDescriptor<Integer, Object>(
                            "vcState",
                            Integer.class,
                            Object.class
                        
                        ));
                }
                
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    vcState.put(value.getVc(), new Object());
    
                    List<Integer> list = AtguiguUtil.toList(vcState.keys());
                    out.collect(ctx.getCurrentKey() + "  " + list);
                    
                }
            })
            .print();
        
        env.execute();
    }
    
}
